import * as API from '../../apis/add'
import {inject, observer} from 'mobx-react';
import {Card,Icon,Popover,Button,AutoComplete,Menu,message} from 'antd';
import {WeaInputSearch,WeaTools,WeaErrorPage,WeaLocaleProvider} from 'ecCom'
import * as mobx from 'mobx'
import isEqual from 'lodash/isEqual';
import forEach from 'lodash/forEach';
import indexOf from 'lodash/indexOf';
const getLabel = WeaLocaleProvider.getLabel;

@inject('wfAddStore')
@observer
class LinkCardItem extends React.Component{
	constructor(props) {
        super(props);
        this.state = {
            width: 0
        }
    }
	componentDidMount(){
		if (!document.getElementsByClassName) {
		    document.getElementsByClassName = function (className, element) {
		        var children = (element || document).getElementsByTagName('*');
		        var elements = new Array();
		        for (var i = 0; i < children.length; i++) {
		            var child = children[i];
		            var classNames = child.className.split(' ');
		            for (var j = 0; j < classNames.length; j++) {
		                if (classNames[j] == className) {
		                    elements.push(child);
		                    break;
		                }
		            }
		        }
		        return elements;
		    };
		}
		let coms = document.getElementsByClassName('centerItem')[0];
		!!coms.offsetWidth && this.setState({width:coms.offsetWidth});
	}
	shouldComponentUpdate(nextProps,nextState) {
		const wfbean = this.props.wfbean;
		const wfbeanNext = nextProps.wfbean;
		const {wfOperateInfo ={}} = nextProps;
		const curOperWfidNext = wfOperateInfo.curOperWfid;
		let needrender = false;
		const _c  = !isEqual(mobx.toJS(this.props.importDataShow),mobx.toJS(nextProps.importDataShow));
		needrender = curOperWfidNext === wfbeanNext.id
				&& (!isEqual(this.props.wfOperateInfo,nextProps.wfOperateInfo) 
				|| _c)
        return !isEqual(wfbean, wfbeanNext) || needrender
			|| this.props.iscommon !== nextProps.iscommon
			|| this.props.num !== nextProps.num
			|| this.state.width !== nextState.width;
    }
	render(){
		const {width} = this.state;
		const {wfbean,importDataShow,iscommon,num,wfOperateInfo ={},actions,user,wfAddStore} = this.props;
		const {initParams = {}} = wfAddStore;
		const {isNeedCollect = '1'} = initParams;
		const {beagenters,belongtoUsers,wfColl,isImportWf,id,name} = wfbean;
		const {showBeagenters = false,showImportWf = false,isDisableImportWfMenu=false} = wfOperateInfo;
		
		const isagent = !!beagenters && beagenters.length > 0;
		const isBelong = !!belongtoUsers && belongtoUsers.length > 0;
		const hasImportDate = !!importDataShow && importDataShow.length > 0;
		let importMenuItem = [];
		hasImportDate && importDataShow.map((b,i)=>{
			if(i < 5) {
				importMenuItem.push(<Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@uujtu3@${i}`} title={b.title} disabled={isDisableImportWfMenu}>
						<a style={{'padding':'0 12px 0 20px'}} onClick={()=>actions.importWf(b,id)}><span dangerouslySetInnerHTML={{__html: b.value}}></span></a>
				</Menu.Item>);
			}
		});

		const isImport = isImportWf && isImportWf == "1";
		const colected = wfColl=="1";
		const isCreateBtn = isagent || isBelong;

		const agentWidth = isImport && !iscommon ? width-90 : ((isImport || !iscommon) ? width-60 : width-30);
		const importWidth = iscommon ? width-30 : width-60;
       	const colorarray = ["#55D2D4","#B37BFA","#FFC62E","#8DCE36","#37B2FF","#FF9537","#FF5E56"];
		return (
				<div className="centerItem" key={id} onMouseLeave={this.hideOperArea} >
					{iscommon && <span style={{color:colorarray[num%7],fontSize:'30px',float:'left',marginLeft:20}}><i className={`icon-coms-${num + 1}`} /></span>}
					<div className="fontItem" style={{'width': iscommon ? '60%':'100%'}}>
						<a onClick={this.onNewRequest.bind(this,id,'',0,0)} target="_blank" title={name}>{name}</a>
					</div>

					<div className= "imageItem" style={{"display":"none"}}>
							{isCreateBtn &&
								<div className='wea-add-drop-btn'>
								 	<span className='wea-add-drop-btn-area' onClick={this.agentCreate}>
								 		<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@mc543i`} title={getLabel(84522,"选择创建身份")} type="team"/>
								 	</span>
								 	{showBeagenters &&
								 		<div className='wea-add-drop-content' style={{width:agentWidth}}>
								 			<div className='wea-add-drop-btn-on' onClick={this.agentCreate}>
								 				<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@lifwlx`} title={getLabel(84522,"选择创建身份")} type="team"/>
								 			</div>
								 			{isBelong &&
								 				<div>
										 			<span>{getLabel(386168,"次账号")}</span>
										 			<Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@erztq4`}>
											 			{belongtoUsers.map(b=>{
															return <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@0o7zda@${b.id}`}>
																<a onClick={this.onNewRequest.bind(this,id,b.id,0,0)} target="_blank">
																	{b.subcompanyName && (b.subcompanyName + '/')}
																	{b.departmentName && ( b.departmentName + '/')}
																	{b.jobtitlename && (b.jobtitlename)}
																</a>
															</Menu.Item>})
														}
										 			</Menu>
									 			</div>
								 			}
								 			{isagent &&
								 				<div>
										 			<span>{getLabel(84523,"代理他人创建")}</span>
										 			<Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@q3wgus`}>
											 			{beagenters.map(b=>{
															return <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@zdyv90@${b.id}`}>
																<a onClick={this.onNewRequest.bind(this,id,'',b.id,1)} target="_blank">
																	{b.lastname}（{b.subcompanyName && (b.subcompanyName + '/')}{b.departmentName && (b.departmentName + '/')}{b.jobtitlename && (b.jobtitlename)}）
																</a>
															</Menu.Item>})
														}
										 			</Menu>
									 			</div>
								 			}
								 		</div>
								 	}
								</div>
							}
							{isImport &&
								<div className='wea-add-drop-btn' >
									<span className='wea-add-drop-btn-area' onClick={this.importWf}>
									 	<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@yerxm4`} title={getLabel(24270,"导入流程")} type="download"/>
								 	</span>
								 	{showImportWf &&
								 		<div className='wea-add-drop-content' style={{width:importWidth}}>
								 			<div className='wea-add-drop-btn-on' onClick={this.importWf}>
								 				<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@4tf5vj`} title={getLabel(24270,"导入流程")} type="download"/>
								 			</div>
								 			<WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@juuqld`} onSearchChange={v=>actions.setImportSearchValue(v)}/>
								 			{hasImportDate ? <Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@l3un9u`} style={{marginTop:10}}>
									 			{importMenuItem}
								 				</Menu> : <div>{getLabel(385021,"数据为空")}</div>
								 			}
								 		</div>
								 	}
								</div>
							}
							{!iscommon && isNeedCollect === '1' &&
								<div className='wea-add-drop-btn' >
									<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@ijpobg`} type={colected ? "star" : "star-o" } title={colected ? getLabel(129753,"取消收藏") : getLabel(386169,"加入我的收藏")} onClick={this.addWorkflow.bind(this,colected ? '0' : '1')}/>
								</div>
							}
					</div>
				</div>
			   )
	}
	//新建流程
	onNewRequest = (wfid,f_weaver_belongto_userid,beagenter,isagent,e) => {
		const {cardItemParams ={},wfAddStore} = this.props;
        let paramstr = `workflowid=${wfid}&isagent=${isagent}&beagenter=${beagenter}&f_weaver_belongto_userid=${f_weaver_belongto_userid}&f_weaver_belongto_usertype=0`;
        forEach(cardItemParams,(v,k)=>{
            paramstr += `&${k}=${v}`;
		})
		//计数
		//jQuery.post('/workflow/request/AddWorkflowUseCount.jsp',{wfid:wfid});
		const { unSupportSPAWf } = wfAddStore;
		const supportSPA = indexOf(unSupportSPAWf,wfid) === -1;
		const url = supportSPA ? "/spa/workflow/static4form/index.html?_rdm="+new Date().getTime()+"#/main/workflow/req?iscreate=1&" : "/workflow/request/CreateRequestForward.jsp?";
		this.openFullWindowHaveBar(url+paramstr);
	}
	
	openFullWindowHaveBar = (url) => {
		var redirectUrl = url;
		var width = screen.availWidth - 10;
		var height = screen.availHeight - 50;
		var szFeatures = "top=0,";
		szFeatures += "left=0,";
		szFeatures += "width=" + width + ",";
		szFeatures += "height=" + height + ",";
		szFeatures += "directories=no,";
		szFeatures += "status=yes,toolbar=no,location=no,";
		szFeatures += "menubar=no,";
		szFeatures += "scrollbars=yes,";
		szFeatures += "resizable=yes"; //channelmode
		window.open(redirectUrl, "", szFeatures);
	}
	
	//添加收藏
	addWorkflow = (colected) => {
		const {wfbean,actions} = this.props;
		actions.doAddWfToColl(wfbean,colected);
	}
	//控制显示
	hideOperArea = (indexid) => {
		const {actions,wfbean,wfOperateInfo} = this.props;
		const wfid = wfbean.id;
		if(wfOperateInfo.curOperWfid == wfid){
			actions.setShowBeagenters(wfid, false);
			actions.setShowImportWf(wfid, false);
		}
	}
	//代理创建
	agentCreate = () => {
		const {actions,wfbean,wfOperateInfo = {}} = this.props;
		const wfid = wfbean.id;
		const {showBeagenters = false,showImportWf = false} = wfOperateInfo;
		actions.setShowBeagenters(wfid, !showBeagenters);
		if(showImportWf){
			actions.setShowImportWf(wfid, false);
		}
	}
	//流程导入
	importWf = () => {
		const {actions,wfbean,wfOperateInfo = {},user} = this.props;
		const wfid = wfbean.id;
		const {showImportWf = false,showBeagenters = false} = wfOperateInfo;
		if(showImportWf){
			actions.setShowImportWf(wfid, false);
		}else{
			const userid = user.id;
			const params = {
				'f_weaver_belongto_userid':userid,
				"f_weaver_belongto_usertype":"0",
				"workflowid":wfbean.id,
				"location":"Boston",
				"importuser":userid
			};
			//actions.setImportSearchValue('');
			actions.getImportData(params);
		}
		if(showBeagenters){
			actions.setShowBeagenters(wfid, false);
		}
	}
}

export default LinkCardItem

//export default WeaTools.tryCatch(React, 
//  props => <WeaErrorPage msg={ props.error ? props.error : '对不起，该页面异常，请联系管理员！'} />,
//  {error: ""}
//)(LinkCardItem);